<template>
  <el-container>
    <el-main>
      <el-row :gutter="16">
        <!-- 左侧表格 -->
        <el-col :span="12">
          <el-card>
            <div slot="header" class="clearfix">
              <span>第一步：单击行选择商品</span>
            </div>
            <el-form :inline="true" :model="searchForm">
              <el-form-item label="商品:">
                <el-input v-model="searchForm.materialParam" placeholder="条码、名称等查询" />
              </el-form-item>
              <el-form-item label="类别">
                <el-select
                  v-model="searchForm.categoryId"
                  placeholder="请选择类别"
                  style="width: 150px;"
                >
                  <el-option
                    v-for="item in categoryTree"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button style="margin-left: 8px" @click="handleReset">重置</el-button>
              </el-form-item>
            </el-form>
            <el-table
              :data="productData"
              @row-click="handleRowClick"
              style="width: 100%"
            >
              <el-table-column
                v-for="column in productColumns"
                :key="column.dataIndex"
                :prop="column.dataIndex"
                :label="column.title"
                :width="column.width"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row[column.dataIndex] }}</span>
                </template>
              </el-table-column>
            </el-table>
            <!-- 新增分页组件 -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pagination.current"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total"
              style="margin-top: 16px; text-align: right;"
            >
            </el-pagination>
          </el-card>
        </el-col>

        <!-- 右侧表格 -->
        <el-col :span="12">
          <el-card>
            <div slot="header" class="clearfix">
              <span>第二步：为选中的商品设置物料及工序</span>
            </div>

            <el-form :inline="true" style="text-align: center;">
              <el-form-item label="商品条码" style="display: inline-block; margin-right: 16px;" :label-width="'80px'">
                <el-input
                  v-model="selectedProductBarCode"
                  :readonly="true"
                  style="width: 200px;"
                />
              </el-form-item>
              <el-form-item label="商品名称" style="display: inline-block;" :label-width="'80px'">
                <el-input
                  v-model="selectedProductName"
                  :readonly="true"
                  style="width: 200px;"
                />
              </el-form-item>
            </el-form>

            <el-tabs v-model="activeTab">
              <el-tab-pane label="1.所需物料" name="1">
                <div style="margin-bottom: 16px;">
                  <el-button size="mini" type="primary" @click="handleAddMaterial">新增</el-button>
                  <el-button size="mini" type="danger" @click="handleDeleteMaterial">删除</el-button>
                  <el-button size="mini" @click="handleImportMaterial">导入</el-button>
                  <el-button size="mini" @click="handleExportMaterial">导出</el-button>
                </div>
                <el-table
                  :data="materialData"
                  style="width: 100%"
                  @selection-change="handleSelectionChange"
                >
                  <!-- 新增多选列 -->
                  <el-table-column
                    type="selection"
                    width="55"
                  >
                  </el-table-column>
                  <!-- 新增操作列 -->
                  <el-table-column
                    label="操作"
                    width="100"
                  >
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        @click="handleEdit(scope.row)"
                      >
                        编辑
                      </el-button>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-for="column in materialColumns"
                    :key="column.dataIndex"
                    :prop="column.dataIndex"
                    :label="column.title"
                    :width="column.width"
                  >
                    <template slot-scope="scope">
                      <span>{{ scope.row[column.dataIndex] }}</span>
                    </template>
                  </el-table-column>

                </el-table>
              </el-tab-pane>
              <el-tab-pane label="2.生产工序" name="2">
                <div style="margin-bottom: 16px;">
                  <el-button size="mini" type="primary" @click="handleAddProcess">新增</el-button>
                  <el-button size="mini" type="danger" @click="handleDeleteProcess">删除</el-button>
                </div>
                <el-table
                  :data="productionProcessData"
                  style="width: 100%"
                  @selection-change="handleSelectionChangeProcess"
                >
                  <!-- 新增多选列 -->
                  <el-table-column
                    type="selection"
                    width="55"
                  >
                  </el-table-column>
                  <!-- 新增操作列 -->
                  <el-table-column
                    label="操作"
                    width="100"
                  >
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        @click="handleEditProcess(scope.row)"
                      >
                        编辑
                      </el-button>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-for="column in productionProcessColumns"
                    :key="column.dataIndex"
                    :prop="column.dataIndex"
                    :label="column.title"
                    :width="column.width"
                  >
                    <template slot-scope="scope">
                      <span v-if="column.dataIndex === 'billingMethod'">
                        {{ scope.row[column.dataIndex] === 0 ? '计时' : scope.row[column.dataIndex] === 1 ? '计件' : scope.row[column.dataIndex] }}
                      </span>
                      <span v-else-if="column.dataIndex === 'responsiblePerson'">
                        {{ getResponsiblePersonName(scope.row[column.dataIndex]) }}
                      </span>
                      <span v-else>{{ scope.row[column.dataIndex] }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </el-col>
      </el-row>
    </el-main>

    <import-file-modal ref="modalImportForm" @ok="fetchMaterialData"></import-file-modal>

    <!-- 新增物料弹出框 -->
    <el-dialog title="新增/编辑物料" :visible.sync="addMaterialDialogVisible" width="30%" :close-on-click-modal="false" z-index="100">
      <el-form :model="addMaterialForm" :rules="addMaterialRules" ref="addMaterialForm" label-width="80px" size="small">
        <el-form-item label="条码:" prop="bomBarCode">
          <JSelectList kind="material" @change="handleBarMaterialChange" :multi="false"
                       :value="addMaterialForm.bomBarCode"/>
        </el-form-item>
        <el-form-item label="名称:" prop="name">
          <el-input v-model="addMaterialForm.name" readonly style="width: 88%"></el-input>
        </el-form-item>
        <el-form-item label="单位:" prop="commodityUnit">
          <el-input v-model="addMaterialForm.commodityUnit" readonly style="width: 88%"></el-input>
        </el-form-item>
        <el-form-item label="多属性:" prop="sku">
          <el-input v-model="addMaterialForm.sku" readonly style="width: 88%"></el-input>
        </el-form-item>
        <el-form-item label="采购价:" prop="purchasePrice">
          <el-input v-model="addMaterialForm.purchasePrice" readonly style="width: 88%"></el-input>
        </el-form-item>
        <el-form-item label="数量:" prop="num">
          <el-input v-model="addMaterialForm.num" placeholder="请输入数量" @input="calculateAllPrice" style="width: 88%"></el-input>
        </el-form-item>
        <el-form-item label="费用:" prop="allPrice">
          <el-input v-model="addMaterialForm.allPrice" readonly style="width: 88%"></el-input>
        </el-form-item>
        <el-form-item label="备注:" prop="remarks">
          <el-input v-model="addMaterialForm.remarks" placeholder="请输入备注" style="width: 88%"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addMaterialDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddMaterialForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增生产工序弹出框 -->
    <el-dialog title="新增/编辑生产工序" :visible.sync="addProcessDialogVisible" width="30%" :close-on-click-modal="false">
      <el-form :model="addProcessForm" :rules="addProcessRules" ref="addProcessForm" label-width="85px" size="small">
        <el-form-item label="执行顺序:" prop="processName">
          <el-input v-model="addProcessForm.executionOrder" placeholder="请输入工序名称"></el-input>
        </el-form-item>
        <el-form-item label="工序名称:" prop="processName">
          <el-input v-model="addProcessForm.processName" placeholder="请输入工序名称"></el-input>
        </el-form-item>
        <el-form-item label="负责人:" prop="responsiblePerson">
          <el-select v-model="addProcessForm.responsiblePerson" placeholder="请选择负责人" style="width: 100%;">
            <el-option
              v-for="person in responsiblePersonList"
              :key="person.id"
              :label="person.userName"
              :value="person.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计费方式:" prop="billingMethod">
          <el-select v-model="addProcessForm.billingMethod" placeholder="请选择计费方式" style="width: 100%;">
            <el-option label="计时" value="0"></el-option>
            <el-option label="计件" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工价:" prop="price">
          <el-input v-model="addProcessForm.laborCost" placeholder="请输入工价"></el-input>
        </el-form-item>
        <el-form-item label="备注:" prop="remarks">
          <el-input v-model="addProcessForm.remarks" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addProcessDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddProcessForm">确 定</el-button>
      </span>
    </el-dialog>

  </el-container>
</template>

<script>
import {getUserList, queryMaterialCategoryTreeList} from '@/api/api';
import {downFile, getAction, postAction, putAction} from '@/api/manage';
import ImportFileModal from '@/components/tools/ImportFileModal'
import {getNowFormatStr} from "@/utils/util";
import JSelectList from "@comp/jeecgbiz/JSelectList.vue";

export default {
  components: {
    JSelectList,
    ImportFileModal // 注册 ImportFileModal 组件
  },
  data() {
    return {
      searchForm: {
        materialParam: '',
        categoryId: undefined
      },
      categoryTree: [],
      responsiblePersonList:[],
      productColumns: [
        { title: '条码', dataIndex: 'mBarCode', key: 'mBarCode' },
        { title: '名称', dataIndex: 'name', key: 'name' },
        { title: '规格', dataIndex: 'standard', key: 'standard' },
        { title: '型号', dataIndex: 'model', key: 'model' },
        { title: '类别', dataIndex: 'categoryName', key: 'categoryName' },
        { title: '单位', dataIndex: 'unit', key: 'unit' }
      ],
      productData: [],
      selectedProductId: null,
      selectedProductBarCode: '',
      selectedProductName: '',
      materialColumns: [
        { title: '条码', dataIndex: 'bomBarCode', width: 100 },
        { title: '名称', dataIndex: 'name', width: 150 },
        { title: '规格', dataIndex: 'standard', width: 100 },
        { title: '型号', dataIndex: 'model', width: 100 },
        { title: '单位', dataIndex: 'commodityUnit', width: 80 },
        { title: '多属性', dataIndex: 'sku', width: 100 },
        { title: '数量', dataIndex: 'num', width: 80 },
        { title: '费用', dataIndex: 'allPrice', width: 80 },
        { title: '备注', dataIndex: 'remarks', width: 80 }
      ],
      materialData: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      activeTab: '1', // 新增变量，用于控制当前激活的tab页
      productionProcessData: [], // 新增数据源，用于存储生产工序数据
      // 修改生产工序列定义，添加更多字段
      productionProcessColumns: [
        { title: '执行顺序', dataIndex: 'executionOrder', key: 'executionOrder' },
        { title: '工序名称', dataIndex: 'processName', key: 'processName' },
        { title: '负责人', dataIndex: 'responsiblePerson', key: 'responsiblePerson' },
        { title: '计费方式', dataIndex: 'billingMethod', key: 'billingMethod' },
        { title: '工价', dataIndex: 'laborCost', key: 'laborCost' },
        { title: '备注', dataIndex: 'remarks', key: 'remarks' }
      ],
      importUrl: '/bom/importExcel', // 导入接口地址
      selectedMaterialIds: [], // 新增变量，用于存储选中的物料ID
      selectedProcessIds: [], // 新增变量，用于存储选中的工序ID
      addMaterialDialogVisible: false,
      addMaterialForm: {
        id: '',
        bomBarCode: '',
        name: '',
        commodityUnit: '',
        sku: '',
        purchasePrice: '',
        num: '',
        allPrice: '',
        remarks: ''
      },
      addMaterialRules: {
        bomBarCode: [{ required: true, message: '请选择商品', trigger: 'blur' }],
        num: [{ required: true, message: '请输入数量', trigger: 'blur' }]
      },
      // 新增生产工序相关变量
      addProcessDialogVisible: false,
      addProcessForm: {
        id: '',
        executionOrder: '',
        processName: '',
        responsiblePerson: '',
        billingMethod: '',
        laborCost: '',
        remarks: ''
      },
      // 新增生产工序表单验证规则
      addProcessRules: {
        executionOrder: [{ required: true, message: '请输入执行顺序', trigger: 'blur' }],
        processName: [{ required: true, message: '请输入工序名称', trigger: 'blur' }],
        responsiblePerson: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
        billingMethod: [{ required: true, message: '请输入计费方式', trigger: 'blur' }],
        laborCost: [{ required: true, message: '请输入工价', trigger: 'blur' }]
      }
    };
  },
  methods: {
    handleSearch() {
      this.pagination.current = 1; // 重置当前页码
      this.fetchProductData();
    },
    handleReset() {
      this.searchForm = {
        materialParam: '',
        categoryId: undefined
      };
      this.pagination.current = 1; // 重置当前页码
      this.fetchProductData();
    },
    fetchProductData() {
      const params = {
        search: JSON.stringify({
          materialParam: this.searchForm.materialParam,
          categoryId: this.searchForm.categoryId
        }),
        currentPage: this.pagination.current,
        pageSize: this.pagination.pageSize
      };
      getAction('/material/list', params).then((res) => {
        if (res.code === 200) {
          this.productData = res.data.rows;
          this.pagination.total = res.data.total;
        } else {
          console.error('Failed to fetch product data:', res);
        }
      }).catch((err) => {
        console.error('Error fetching product data:', err);
      });
    },
    handleRowClick(record) {
      this.selectedProductBarCode = record.mBarCode;
      this.selectedProductName = record.name;
      this.selectedProductId = record.id; // 设置选中商品的id
      this.fetchMaterialData();
      this.fetchProductionProcessData(); // 调用方法获取生产工序数据
    },
    fetchMaterialData() {
        if (!this.selectedProductId) {
            this.$message.warning('请先选择商品');
            return;
        }
        const params = {
            productId: this.selectedProductId
        };
        getAction('/bom/getBomMaterialsByProductId', params).then((res) => {
            if (res.code === 200) {
                this.materialData = res.data;
            } else {
                console.error('Failed to fetch material data:', res);
                this.$message.error('获取物料数据失败');
            }
        }).catch((err) => {
            console.error('Error fetching material data:', err);
            this.$message.error('获取物料数据失败');
        });
    },
    fetchProductionProcessData() {
      if (!this.selectedProductId) {
        this.$message.warning('请先选择商品');
        return;
      }
      const params = {
        productId: this.selectedProductId
      };
      getAction('/bom/getProductionProcessesByProductId', params).then((res) => {
        if (res.code === 200) {
          this.productionProcessData = res.data;
        } else {
          console.error('Failed to fetch production process data:', res);
          this.$message.error('获取生产工序数据失败');
        }
      }).catch((err) => {
        console.error('Error fetching production process data:', err);
        this.$message.error('获取生产工序数据失败');
      });
    },
    loadTreeData() {
      queryMaterialCategoryTreeList({ id: '' }).then((res) => {
        if (res) {
          this.categoryTree = res;
        }
      });
    },
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.fetchProductData();
    },
    handleCurrentChange(current) {
      this.pagination.current = current;
      this.fetchProductData();
    },
    handleSelectionChange(selection) {
      this.selectedMaterialIds = selection.map(item => item.id);
    },
    handleDeleteMaterial() {
      if (this.selectedMaterialIds.length === 0) {
        this.$message.warning('请先选择需要删除的物料');
        return;
      }
      var that = this;
      this.$confirm({
        title: "确认删除",
        content: "此操作将永久删除选中的物料, 是否继续?",
        onOk: function () {
          postAction('/bom/deleteBomMaterials', that.selectedMaterialIds).then((res) => {
            if (res.code === 200) {
              that.$message.success('删除成功');
              that.fetchMaterialData();
            } else {
              that.$message.error('删除失败');
            }
          }).catch((err) => {
            console.error('Error deleting materials:', err);
            that.$message.error('删除失败');
          });
        }
      });
    },
    // 新增方法
    handleAddMaterial() {
      if (!this.selectedProductId) {
        this.$message.warning('请先选择商品');
        return;
      }
      this.clearAddMaterialForm(); // 清空表单数据
      this.$nextTick(() => {
        this.$refs['addMaterialForm'].resetFields(); // 清空验证信息
      });
      this.addMaterialDialogVisible = true;
    },
    submitAddMaterialForm() {
      this.$refs['addMaterialForm'].validate((valid) => {
        if (valid) {
          const params = { ...this.addMaterialForm, proMaterialId: this.selectedProductId };
          let promise;
          let successMessage;
          let errorMessage;

          if (this.addMaterialForm.id) {
            // 编辑操作
            promise = putAction('/bom/updateBomMaterial', params);
            successMessage = '编辑物料成功';
            errorMessage = '编辑物料失败';
          } else {
            // 新增操作
            promise = postAction('/bom/addBomMaterial', params);
            successMessage = '新增物料成功';
            errorMessage = '新增物料失败';
          }

          promise.then((res) => {
            if (res.code === 200) {
              this.$message.success(successMessage);
              this.fetchMaterialData();
              this.addMaterialDialogVisible = false;
              this.clearAddMaterialForm(); // 清空表单数据
              this.$nextTick(() => {
                this.$refs['addMaterialForm'].resetFields(); // 清空验证信息
              });
            } else {
              this.$message.error(errorMessage);
            }
          }).catch((err) => {
            console.error('Error saving material:', err);
            this.$message.error(errorMessage);
          });
        }
      });
    },
    handleBarMaterialChange(mBarCode) {
      if (mBarCode) {
        this.addMaterialForm.bomBarCode = mBarCode;
        getAction('/material/getMaterialByBarCode', { barCode: mBarCode, mpList: '' }).then((res) => {
          if (res.code === 200 && res.data && res.data[0]) { // 增加非空判断
            //名称，单位，多属性，采购价
            console.log('Material data:', res.data);
            this.addMaterialForm.name = res.data[0].name;
            this.addMaterialForm.commodityUnit = res.data[0].commodityUnit;
            this.addMaterialForm.sku = res.data[0].sku;
            this.addMaterialForm.purchasePrice = res.data[0].purchaseDecimal;
            this.addMaterialForm.num = 1;
            if(this.addMaterialForm.purchasePrice !== null&&this.addMaterialForm.purchasePrice !== '') {
               this.addMaterialForm.allPrice = parseFloat(this.addMaterialForm.purchasePrice).toFixed(2);
            }
          }
        }).catch((err) => {
          console.error('Error fetching material by barcode:', err);
          this.$message.error('获取物料信息失败');
        });
      }
    },
    handleEdit(record) {
      this.addMaterialForm = Object.assign({}, this.addMaterialForm, {
        id: record.id,
        bomBarCode: record.bomBarCode,
        name: record.name,
        commodityUnit: record.commodityUnit,
        sku: record.sku,
        purchasePrice: record.purchasePrice,
        num: record.num,
        allPrice: record.allPrice,
        remarks: record.remarks
      });

      // 显示添加物料对话框用于编辑
      this.addMaterialDialogVisible = true;

      // 重置表单验证
      this.$nextTick(() => {
        this.$refs['addMaterialForm'].resetFields();
      });
    },
    handleImportMaterial() {
      if (!this.selectedProductId) {
        this.$message.warning('请先选择商品');
        return;
      }
      let importExcelUrl = `${this.importUrl}?productId=${this.selectedProductId}`; // 修改导入URL，添加商品id参数
      let templateUrl = '/doc/bom_material_template.xls';
      let templateName = '物料Excel模板[下载]';
      this.$refs.modalImportForm.initModal(importExcelUrl, templateUrl, templateName);
      this.$refs.modalImportForm.title = "物料导入";
    },
    handleExportMaterial() {
      if (!this.selectedProductId) {
          this.$message.warning('请先选择商品');
          return;
      }
      const exportUrl = `/bom/exportBomMaterials?productId=${this.selectedProductId}`;
      let fileName = this.selectedProductBarCode  + '_' + this.selectedProductName + '_BOM信息';
      downFile(exportUrl, {}).then((data)=>{
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName+'.xls')
        }else{
          let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '_' + getNowFormatStr()+'.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },
    calculateAllPrice() {
      if (this.addMaterialForm.num && this.addMaterialForm.purchasePrice) {
        this.addMaterialForm.allPrice = (parseFloat(this.addMaterialForm.num) * parseFloat(this.addMaterialForm.purchasePrice)).toFixed(2);
      } else {
        this.addMaterialForm.allPrice = '';
      }
    },
    clearAddMaterialForm() {
      this.addMaterialForm = {
        bomBarCode: '',
        name: '',
        commodityUnit: '',
        sku: '',
        purchasePrice: '',
        num: '',
        allPrice: '',
        remarks: ''
      };
    },

    // 新增生产工序相关方法
    handleAddProcess() {
      if (!this.selectedProductId) {
        this.$message.warning('请先选择商品');
        return;
      }
      this.clearAddProcessForm(); // 清空表单数据
      this.$nextTick(() => {
        this.$refs['addProcessForm'].resetFields(); // 清空验证信息
      });
      this.addProcessDialogVisible = true;
    },
    handleDeleteProcess() {
      if (this.selectedProcessIds.length === 0) {
        this.$message.warning('请先选择需要删除的生产工序');
        return;
      }
      var that = this;
      this.$confirm({
        title: "确认删除",
        content: "此操作将永久删除选中的生产工序, 是否继续?",
        onOk: function () {
          postAction('/bom/deleteProductionProcesses', that.selectedProcessIds).then((res) => {
            if (res.code === 200) {
              that.$message.success('删除成功');
              that.fetchProductionProcessData();
            } else {
              that.$message.error('删除失败');
            }
          }).catch((err) => {
            console.error('Error deleting production processes:', err);
            that.$message.error('删除失败');
          });
        }
      });
    },

    handleEditProcess(record) {
      this.addProcessForm = Object.assign({}, this.addProcessForm, {
        id: record.id,
        executionOrder: record.executionOrder,
        processName: record.processName,
        responsiblePerson: record.responsiblePerson,
        billingMethod: record.billingMethod,
        laborCost: record.laborCost,
        remarks: record.remarks
      });

      // 显示新增/编辑生产工序对话框用于编辑
      this.addProcessDialogVisible = true;

      // 重置表单验证
      this.$nextTick(() => {
        this.$refs['addProcessForm'].resetFields();
      });
    },
    submitAddProcessForm() {
      this.$refs['addProcessForm'].validate((valid) => {
        if (valid) {
          const params = { ...this.addProcessForm, proMaterialId: this.selectedProductId };
          let promise;
          let successMessage;
          let errorMessage;

          if (this.addProcessForm.id) {
            // 编辑操作
            promise = putAction('/bom/updateProductionProcess', params);
            successMessage = '编辑生产工序成功';
            errorMessage = '编辑生产工序失败';
          } else {
            // 新增操作
            promise = postAction('/bom/addProductionProcess', params);
            successMessage = '新增生产工序成功';
            errorMessage = '新增生产工序失败';
          }

          promise.then((res) => {
            if (res.code === 200) {
              this.$message.success(successMessage);
              this.fetchProductionProcessData();
              this.addProcessDialogVisible = false;
              this.clearAddProcessForm(); // 清空表单数据
              this.$nextTick(() => {
                this.$refs['addProcessForm'].resetFields(); // 清空验证信息
              });
            } else {
              this.$message.error(errorMessage);
            }
          }).catch((err) => {
            console.error('Error saving production process:', err);
            this.$message.error(errorMessage);
          });
        }
      });
    },

    clearAddProcessForm() {
      this.addProcessForm = {
        id: '',
        executionOrder:  '',
        processName: '',
        responsiblePerson: '',
        billingMethod: '',
        laborCost: '',
        remarks: ''
      };
    },

    handleSelectionChangeProcess(selection) {
      this.selectedProcessIds = selection.map(item => item.id);
    },
    initUser() {
      getUserList({}).then((res)=>{
        if(res) {
          this.responsiblePersonList = res;
        }
      });
    },
    getResponsiblePersonName(id) {
      const person = this.responsiblePersonList.find(item => item.id === id);
      return person ? person.userName : id;
    },
  },
  mounted() {
    this.loadTreeData();
    this.fetchProductData();
    this.initUser();
  }
};
</script>

<style scoped>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style>